package cn.community.care.module.system.service.orders;

import cn.community.care.framework.common.exception.ServiceException;
import cn.community.care.framework.security.core.util.SecurityFrameworkUtils;
import cn.community.care.module.system.dal.dataobject.hotproducts.HotProductsDO;
import cn.community.care.module.system.dal.dataobject.shoppingcart.ShoppingCartDO;
import cn.community.care.module.system.dal.dataobject.task.TaskDO;
import cn.community.care.module.system.dal.mysql.hotproducts.HotProductsMapper;
import cn.community.care.module.system.dal.mysql.shoppingcart.ShoppingCartMapper;
import cn.community.care.module.system.dal.mysql.task.TaskMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.community.care.module.system.controller.admin.orders.vo.*;
import cn.community.care.module.system.dal.dataobject.orders.OrdersDO;
import cn.community.care.framework.common.pojo.PageResult;
import cn.community.care.framework.common.pojo.PageParam;
import cn.community.care.framework.common.util.object.BeanUtils;

import cn.community.care.module.system.dal.mysql.orders.OrdersMapper;

import javax.annotation.Resource;

import static cn.community.care.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.community.care.module.system.enums.ErrorCodeConstants.*;

/**
 * 订单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrdersServiceImpl implements OrdersService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private HotProductsMapper hotProductsMapper;
    private final static String ORDER_NUMBER_PREFIX = "CPDD";

    @Resource
    private TaskMapper taskMapper;

    @Override
    public Long createOrders(OrdersSaveReqVO createReqVO) {
        //获取当日期戳
        long currentTime = System.currentTimeMillis();
        String orderNumber = ORDER_NUMBER_PREFIX + Long.toString(currentTime);
        createReqVO.setOrderNumber(orderNumber);
        createReqVO.setOrderStatus("1");
        // 插入
        OrdersDO orders = BeanUtils.toBean(createReqVO, OrdersDO.class);
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        orders.setUserId(userId);
        ordersMapper.insert(orders);
        // 返回
        return orders.getId();
    }

    @Override
    public void updateOrders(OrdersSaveReqVO updateReqVO) {
        // 校验存在
        validateOrdersExists(updateReqVO.getId());
        //判断是否为取消支付，如果为取消支付则需要把对应的库存放回去。
        if ("3".equals(updateReqVO.getOrderStatus())) {
            ShoppingCartDO shoppingCartDO = shoppingCartMapper.selectById(updateReqVO.getCartId());
            Integer quantity = shoppingCartDO.getQuantity();
            HotProductsDO hotProductsDO = hotProductsMapper.selectById(shoppingCartDO.getProductId());
            String number = hotProductsDO.getNumber();
            Integer integer = Integer.valueOf(number);
            int num = integer + quantity;
            hotProductsDO.setNumber(Integer.toString(num));
            hotProductsMapper.updateById(hotProductsDO);
        }
        // 更新
        OrdersDO updateObj = BeanUtils.toBean(updateReqVO, OrdersDO.class);
        ordersMapper.updateById(updateObj);
    }

    @Transactional
    @Override
    public void updateOrdersByService(OrdersSaveReqVO updateReqVO) {
        OrdersDO updateObj = BeanUtils.toBean(updateReqVO, OrdersDO.class);
        ordersMapper.updateById(updateObj);
        TaskDO taskDO = taskMapper.selectById(updateObj.getProductId());
        taskDO.setStatus("1");
        taskMapper.updateById(taskDO);
    }

    @Override
    public void deleteOrders(Long id) {
        // 校验存在
        validateOrdersExists(id);
        // 删除
        ordersMapper.deleteById(id);
    }

    private void validateOrdersExists(Long id) {
        if (ordersMapper.selectById(id) == null) {
//            throw exception(ORDERS_NOT_EXISTS);
        }
    }

    @Override
    public OrdersDO getOrders(Long id) {
        return ordersMapper.selectById(id);
    }

    @Override
    public PageResult<OrdersDO> getOrdersPage(OrdersPageReqVO pageReqVO) {
        return ordersMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<OrdersDO> getOrdersPageByCart(OrdersPageReqVO pageReqVO) {
        return ordersMapper.selectPageByCart(pageReqVO);
    }

    @Override
    public void playOrder(PlayVo playVo) {
        Long[] ids = playVo.getIds();
        ArrayList<OrdersDO> ordersDOS = new ArrayList<>();
        for (Long id : ids) {
            OrdersDO ordersDO = ordersMapper.selectById(id);
            if (Objects.equals(ordersDO.getOrderStatus(), "2")){
                throw new ServiceException(400,"订单已支付");
            }
            ordersDO.setOrderStatus("2");
            ordersDOS.add(ordersDO);
        }

        ordersMapper.updateBatch(ordersDOS);
    }

    public List<Map<String, Object>> countTotalPriceByDayInLast7Days() {
        return ordersMapper.countTotalPriceByDayInLast7Days();
    }

    @Override
    public Double getOrdersCount() {
        //计算库里所有订单的销售总额
        return  ordersMapper.calculateTotalSales();
    }

    @Override
    public Long getCount() {
        return ordersMapper.selectCount();
    }

}